package com.pm.buglist.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pm.buglist.domain.*;
import com.pm.buglist.mapper.*;
import com.pm.buglist.service.ProjectService;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.entity.SysRole;
import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.enums.*;
import com.pm.common.core.redis.RedisCache;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.bean.BeanUtils;
import com.pm.system.mapper.SysDictDataMapper;
import com.pm.system.mapper.SysUserMapper;
import com.github.yitter.idgen.YitIdHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * <p>
 * 项目信息表 服务实现类
 * </p>
 *
 * @author wwm
 * @since 2023-12-14
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Resource
    private ProjectMemberMapper projectMemberMapper;

    @Resource
    private BugsMapper bugsMapper;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private BugsRdHandleMapper rdHandleMapper;

    @Resource
    private BugsQdeHandleMapper qdeHandleMapper;

    @Resource
    private BugDescriptionMapper descriptionMapper;

    @Resource
    private BugAnalysisMapper analysisMapper;

    @Resource
    private SysDictDataMapper dictDataMapper;

    @Resource
    private BugsServiceImpl bugsServiceImpl;

    @Resource
    private RedisCache redisCache;

    @Override
    public List<Project> getProjectList(Project project) {
        if(StringUtils.isEmpty(project.getExportFlag())){
            project.setIds(null);
        }
        return baseMapper.findProjectList(project);
    }

    @Override
//    @Transactional
    public AjaxResult insertProject(Project project) {
        //获取登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //验证项目是否存在系统
        String projectNo = project.getProjectNo();
        Project project1 = baseMapper.selectOne(new QueryWrapper<Project>().eq("project_no", projectNo).eq("del_flag", '0'));
        if(!ObjectUtils.isEmpty(project1)){
            return AjaxResult.error("项目编码为:"+projectNo+"的项目已存在，请不要重复添加");
        }
        List<SysRole> roles = loginUser.getUser().getRoles();
        boolean flag=false;
        //品质主管/管理员才能创建项目
        if(loginUser.getUser().isAdmin()){
            flag=true;
        }else {
            for (SysRole role : roles) {
                if(role.getRoleKey().equals(RoleKey.DQA.getCode()) || role.getRoleKey().equals(RoleKey.ADMIN.getCode())){
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            return AjaxResult.error("你没有权限执行此操作!");
        }
        //封装项目成员map
//        Map<String, Long> map = getMemberMap(project);
//        if(CollectionUtils.isEmpty(map)){
//            return AjaxResult.error("项目成员不能为空!");
//        }
        long pjId = YitIdHelper.nextId();
        //open 状态
        project.setStatus(ProjectStatus.OPEN.getStatus());
        project.setId(pjId);
        project.setAddUser(loginUser.getUserId());
        project.setAddTime(LocalDateTime.now());
        //添加项目
        baseMapper.insert(project);
        //添加项目成员
//        for (Map.Entry<String, Long> entry : map.entrySet()) {
//            if(!ObjectUtils.isEmpty(entry.getKey())&& !ObjectUtils.isEmpty(entry.getValue())){
//                ProjectMember projectMember = new ProjectMember();
//                projectMember.setId(YitIdHelper.nextId());
//                projectMember.setProjectId(pjId);
//                projectMember.setUserId(entry.getValue());
//                projectMember.setType(entry.getKey());
//                projectMember.setAddUser(loginUser.getUserId());
//                projectMember.setAddTime(LocalDateTime.now());
//                projectMemberMapper.insert(projectMember);
//            }
//
//        }
        //清空项目品牌缓存
        redisCache.deleteObject("ProjectBrand");
        return AjaxResult.success("添加项目成功！");
    }

    @Override
    public AjaxResult OaInsertProject(Project project) {
        try {
            //验证项目是否存在系统
            String projectNo = project.getProjectNo();
            Project project1 = baseMapper.selectOne(new QueryWrapper<Project>().eq("project_no", projectNo).eq("del_flag", '0'));
            if(!ObjectUtils.isEmpty(project1)){//存在就修改
                Project pj = new Project();
                BeanUtils.copyProperties(project,pj);
                pj.setId(project1.getId());
                pj.setUpdateTime(LocalDateTime.now());
                pj.setUpdateUser(project.getAddUser());
                baseMapper.updateById(pj);
            }else {//不存在就新增
                long pjId = YitIdHelper.nextId();
                //open 状态
                project.setStatus(ProjectStatus.OPEN.getStatus());
                project.setId(pjId);
                project.setAddTime(LocalDateTime.now());
                //添加项目
                baseMapper.insert(project);
            }
            //清空项目品牌缓存
            redisCache.deleteObject("ProjectBrand");
            return AjaxResult.success("oa同步添加项目成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("同步oa单数据插入失败:"+e);
        }
    }


    @Override
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public AjaxResult delProject(Long id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                return AjaxResult.error("项目数据不能为空");
            }
            //根据项目id查询项目的bug
            List<Bugs> bugs = bugsMapper.selectList(new QueryWrapper<Bugs>().eq("pid", id));
            if(!CollectionUtils.isEmpty(bugs)){
                List<String> collect = bugs.stream().filter(item -> {
                    return item.getBugStatus().equals(BugsStatus.OPEN.getStatus())||item.getBugStatus().equals(BugsStatus.TRACKING.getStatus());
                }).collect(Collectors.toList()).stream().map(item -> {
                    return item.getBugCode();
                }).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(collect)){
                    return AjaxResult.error("该项目下bugCode为这些"+collect.toString()+"的bug处于Open/Tracking的状态，请废弃之后再执行删除操作");
                }
                //删除项目下的bug
                bugsMapper.batchDeleteBugByPid(id);

            }

            Project project = new Project();
            project.setId(id);
            project.setDelFlag("2");
            project.setUpdateUser(SecurityUtils.getUserId());
            project.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(project);
            //清空项目品牌缓存
            redisCache.deleteObject("ProjectBrand");
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("项目删除异常："+e);
            return AjaxResult.error("删除异常");
        }
    }

    @Override
    public AjaxResult getProjectById(Long id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                return AjaxResult.error("项目数据不能为空");
            }
            Project project = baseMapper.selectById(id);
            //查询项目成员
//            List<ProjectMember> members = projectMemberMapper.selectList(new QueryWrapper<ProjectMember>().eq("project_id", id));
//            if(!CollectionUtils.isEmpty(members)){
//                for (ProjectMember member : members) {
//                    String type = member.getType();
//                    Long userId = member.getUserId();
//                    if(type.equals(PostCode.PJM.getCode())){
//                        project.setPjm(userId);
//                    }else if(type.equals(PostCode.HARDE.getCode())){
//                        project.setHardElectron(userId);
//                    }else if(type.equals(PostCode.HARDP.getCode())){
//                        project.setHardPower(userId);
//                    }else if(type.equals(PostCode.OPTICS.getCode())){
//                        project.setOptics(userId);
//                    }else if(type.equals(PostCode.SOFT.getCode())){
//                        project.setSoft(userId);
//                    }else if(type.equals(PostCode.STU.getCode())){
//                        project.setStructure(userId);
//                    }else if(type.equals(PostCode.NPI.getCode())){
//                        project.setNpi(userId);
//                    }
//                }
//            }
            return AjaxResult.success(project);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取异常");
        }
    }
    //封装项目成员参数
//    private Map<String,Long> getMemberMap(Project project){
//        Map<String, Long> map = new HashMap<>();
//        Long pjm = project.getPjm();
//        Long hardElectron = project.getHardElectron();
//        Long hardPower = project.getHardPower();
//        Long optics = project.getOptics();
//        Long soft = project.getSoft();
//        Long structure = project.getStructure();
//        Long npi = project.getNpi();
//        //封装项目成员参数
//        if(!ObjectUtils.isEmpty(pjm)){
//            map.put(PostCode.PJM.getCode(),pjm);
//        }
//        if(!ObjectUtils.isEmpty(hardElectron)){
//            map.put(PostCode.HARDE.getCode(),hardElectron);
//        }
//        if(!ObjectUtils.isEmpty(hardPower)){
//            map.put(PostCode.HARDP.getCode(),hardPower);
//        }
//        if(!ObjectUtils.isEmpty(optics)){
//            map.put(PostCode.OPTICS.getCode(),optics);
//        }
//        if(!ObjectUtils.isEmpty(soft)){
//            map.put(PostCode.SOFT.getCode(),soft);
//        }
//        if(!ObjectUtils.isEmpty(structure)){
//            map.put(PostCode.STU.getCode(),structure);
//        }
//        if(!ObjectUtils.isEmpty(npi)){
//            map.put(PostCode.NPI.getCode(),npi);
//        }
//        return map;
//    }

    @Override
    @Transactional
    public AjaxResult updateProject(Project project) {
        //获取登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        boolean flag=false;
        //只要品质主管才能创建项目
        if(loginUser.getUser().isAdmin()){
            flag=true;
        }else {
            for (SysRole role : roles) {
                if(role.getRoleKey().equals(RoleKey.DQA.getCode()) || role.getRoleKey().equals(RoleKey.ADMIN.getCode()) ){
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            return AjaxResult.error("你没有权限执行此操作!");
        }
        //项目成员数据
//        Map<String, Long> map = getMemberMap(project);
//        if(CollectionUtils.isEmpty(map)){
//            return AjaxResult.error("项目成员不能为空!");
//        }
        Long id = project.getId();
        if(ObjectUtils.isEmpty(id)){
           return AjaxResult.error("项目数据不能为空");
        }
        project.setUpdateTime(LocalDateTime.now());
        project.setUpdateUser(loginUser.getUserId());
        baseMapper.updateById(project);

//        //先把原来的项目成员删除掉再重新添加
//        projectMemberMapper.delete(new QueryWrapper<ProjectMember>().eq("project_id", id));
//        //添加项目成员
//        for (Map.Entry<String, Long> entry : map.entrySet()) {
//            if(!ObjectUtils.isEmpty(entry.getKey())&& !ObjectUtils.isEmpty(entry.getValue())){
//                ProjectMember projectMember = new ProjectMember();
//                projectMember.setId(YitIdHelper.nextId());
//                projectMember.setProjectId(id);
//                projectMember.setUserId(entry.getValue());
//                projectMember.setType(entry.getKey());
//                projectMember.setAddUser(loginUser.getUserId());
//                projectMember.setAddTime(LocalDateTime.now());
//                projectMemberMapper.insert(projectMember);
//            }
//
//        }
        //清空项目品牌缓存
        redisCache.deleteObject("ProjectBrand");
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult closeProjectById(Long id) {
        try {
            //获取当前登录用户的角色信息
            SysUser user = SecurityUtils.getLoginUser().getUser();
            List<SysRole> roles = user.getRoles();
            Boolean flag=false;
            boolean admin = user.isAdmin();
            if(admin){
                flag=true;
            }else {
                if(!CollectionUtils.isEmpty(roles)){
                    for (SysRole role : roles) {
                        if(role.getRoleKey().equals(RoleKey.DQA.getCode()) || role.getRoleKey().equals(RoleKey.ADMIN.getCode())){
                            flag=true;
                            break;
                        }
                    }
                }
            }
            if(!flag){
                return AjaxResult.error("你没有权限关闭该项目");
            }
            if(org.springframework.util.ObjectUtils.isEmpty(id)){
                return AjaxResult.error("修改的数据不能为空");
            }
            //获取当前项目下的所有bugs信息
            List<Bugs> bugs = bugsMapper.selectList(new QueryWrapper<Bugs>().eq("pid", id).eq("del_flag",'0'));
            //验证所有bugs的状态
            List<Bugs> collect = bugs.stream().filter(item -> {
                return item.getBugStatus().equals(BugsStatus.OPEN.getStatus());
            }).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(collect)){
                List<String> codeList = collect.stream().map(item -> {
                    return item.getBugCode();
                }).collect(Collectors.toList());
                return AjaxResult.error("Bug编码为"+codeList.toString()+"的bug还处于open的状态，此项目还不能关闭");
            }
            Project project = new Project();
            project.setId(id);
            project.setStatus(ProjectStatus.CLOSE.getStatus());//设置为关闭状态
            project.setUpdateTime(LocalDateTime.now());
            project.setUpdateUser(user.getUserId());
            baseMapper.updateById(project);
            return AjaxResult.success("关闭成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("关闭异常");
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public AjaxResult cancelProjectById(Long id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                return AjaxResult.error("项目数据不能为空");
            }
            //根据项目id查询项目的bug
            List<Bugs> bugs = bugsMapper.selectList(new QueryWrapper<Bugs>().eq("pid", id).eq("del_flag",'0'));
            if(!CollectionUtils.isEmpty(bugs)){
                List<String> collect = bugs.stream().filter(item -> {
                    return item.getBugStatus().equals(BugsStatus.OPEN.getStatus());//||item.getBugStatus().equals(BugsStatus.TRACKING.getStatus());
                }).collect(Collectors.toList()).stream().map(item -> {
                    return item.getBugCode();
                }).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(collect)){
                    return AjaxResult.error("该项目下bugCode为这些"+collect.toString()+"的bug处于Open的状态，无法进行取消");//Tracking
                }
                //删除项目下的bug
                bugsMapper.batchDeleteBugByPid(id);

            }

            Project project = new Project();
            project.setId(id);
            project.setStatus(ProjectStatus.CANCEL.getStatus());//取消项目
            project.setUpdateUser(SecurityUtils.getUserId());
            project.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(project);
            //清空项目品牌缓存
            redisCache.deleteObject("ProjectBrand");
            return AjaxResult.success("取消成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("取消异常:"+e);
            return AjaxResult.error("项目取消异常");
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public AjaxResult batchAddProjectBugList(List<Map<Project, List<Bugs>>> list) {
        try {
            if(CollectionUtils.isEmpty(list)){
                return AjaxResult.error("导入失败:导入的数据不能为空");
            }
            Long userId = SecurityUtils.getUserId();
            //遍历导入的数据
            for (Map<Project, List<Bugs>> item : list) {
                for (Map.Entry<Project, List<Bugs>> entry : item.entrySet()) {
                    Project key = entry.getKey();
                    List<Bugs> value = entry.getValue();
                    String projectNo = key.getProjectNo();
                    //验证项目是否存在系统
                    Project project1 = baseMapper.selectOne(new QueryWrapper<Project>().eq("project_no", projectNo).eq("del_flag", '0'));
                    if(!ObjectUtils.isEmpty(project1)){
                        return AjaxResult.error("导入失败:项目编码为:"+projectNo+"的项目已存在，请不要重复添加");
                    }
                    List<String> nameList=new ArrayList<>();
                    //验证bug数据是否合理,主要是查找对应的提报人与责任人信息
                    value.forEach(b->{
                        //提报人姓名
                        String createUserName = b.getCreateUserName();
                        //责任人姓名
                        String respon = b.getRespon();
                        SysUser putUser = userMapper.getUserInfoByUserName(createUserName);
                        if(ObjectUtils.isEmpty(putUser)){
                            nameList.add(createUserName);
                        }else {
                            //设置提报人用户id
                            b.setCreateUser(putUser.getUserId());
                        }
                        SysUser responUser = userMapper.getUserInfoByUserName(respon);
                        if(ObjectUtils.isEmpty(responUser)){
                            nameList.add(respon);
                        }else {
                            //设置责任人用户id
                            b.setUpdateUser(responUser.getUserId());
                        }
                    });
                    //判断是否有找不到对应用户的信息
                    if(!CollectionUtils.isEmpty(nameList)){
                        return AjaxResult.error("导入失败:这个项目("+projectNo+")下的bug的提报人/责任人"+nameList.toString()+"在系统找不到对应的用户信息");
                    }

                    //开始插入数据
                    long Pid = YitIdHelper.nextId();
                    key.setId(Pid);//项目id
                    key.setAddUser(userId);
                    key.setAddTime(LocalDateTime.now());
                    key.setStatus(ProjectStatus.OPEN.getStatus());
                    baseMapper.insert(key);//添加项目
                    //添加bug
                    value.stream().forEach(bug->{
                        Long rdHandle = bug.getUpdateUser();//责任人
                        LocalDateTime updateTime = bug.getUpdateTime();//改善时间
                        Long createUser = bug.getCreateUser();//bug提报人
                        String bugStatusTxt = bug.getBugStatusTxt();//bug状态
                        //TODO 查询bug状态值
                        String bugStatus = dictDataMapper.selectDictLabel(DictDateKey.BUGS_STATUS.getKey(),bugStatusTxt);
//                        Integer bugStatus=null;
//                        if(!StringUtils.isEmpty(dictLabel)){
//                            bugStatus = Integer.valueOf(dictLabel);
//                        }

                        //插入bug
                        bug.setUpdateUser(null);
                        bug.setUpdateTime(null);
                        long bid = YitIdHelper.nextId();
                        bug.setId(bid);
                        bug.setPid(Pid);
                        bug.setBugCode(bugsServiceImpl.createCode());//生成唯一code
                        if(ObjectUtils.isEmpty(bugStatus)){
                            //如果为空查不到，设置为关闭的状态
                            bugStatus=BugsStatus.CLOSE.getStatus();
                        }
                        //截取bug描述获取bug标题
                        String descriptions = bug.getDescriptions();
                        if(descriptions.length()>20){
                            bug.setBugTitle(descriptions.substring(0,20));
                        }else {
                            bug.setBugTitle(descriptions);
                        }
                        bug.setBugStatus(bugStatus);
                        bugsMapper.insert(bug);

                        //责任人
                        BugsRdHandle bugsRdHandle = new BugsRdHandle();
                        bugsRdHandle.setBugId(bid);
                        bugsRdHandle.setStatus("1");//插入时为最新处理人
                        bugsRdHandle.setUserId(rdHandle);//处理人
                        bugsRdHandle.setCreateUser(userId);
                        bugsRdHandle.setCreateTime(LocalDateTime.now());
                        rdHandleMapper.insert(bugsRdHandle);

                        //提报人
                        BugsQdeHandle bugsQdeHandle = new BugsQdeHandle();
                        bugsQdeHandle.setBugId(bid);
                        bugsQdeHandle.setStatus("1");
                        bugsQdeHandle.setUserId(createUser);//品质指派人就是创建人
                        bugsQdeHandle.setCreateUser(userId);
                        bugsQdeHandle.setCreateTime(LocalDateTime.now());
                        qdeHandleMapper.insert(bugsQdeHandle);

                        //插入bugs之后添加bugs描述
                        BugDescription bugDescription = new BugDescription();
                        bugDescription.setBugId(bid);
                        bugDescription.setDescriptions(bug.getDescriptions());
                        bugDescription.setStatus("1");//发布的状态
                        bugDescription.setVersion(bug.getCloseVersion());//描述重点版本是关闭版本
                        bugDescription.setCreateUser(userId);
                        bugDescription.setHandleUser(createUser);//创建人
                        bugDescription.setCreateTime(LocalDateTime.now());
                        descriptionMapper.insert(bugDescription);

                        //插入描述之后插入bug分析
                        BugAnalysis bugAnalysis = new BugAnalysis();
                        bugAnalysis.setBugId(bid);
                        bugAnalysis.setBdId(bugDescription.getId());
                        bugAnalysis.setAnalysis(bug.getAnalysis());//分析
                        bugAnalysis.setBugAnswer(bug.getAnswer());//对策
                        bugAnalysis.setVersion(bug.getCloseVersion());//版本
                        bugAnalysis.setStatus("1");//发布的状态
                        bugAnalysis.setHandleUser(rdHandle);//责任人
                        bugAnalysis.setCreateTime(updateTime);//改善时间
                        //关闭状态的bug，分析要设置关闭标识
                        if(bugStatus.equals(BugsStatus.CLOSE.getStatus())){
                            bugAnalysis.setIsClose("1");
                        }
                        analysisMapper.insert(bugAnalysis);
                    });
                }
            }
            //清空项目品牌缓存
            redisCache.deleteObject("ProjectBrand");
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导入项目BugList数据异常:"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("导入异常！！！");
        }
    }

    @Override
    public AjaxResult openProject(Long id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                return AjaxResult.error("操作的数据不能为空");
            }
            //获取当前登录用户的角色信息
            LoginUser loginUser = SecurityUtils.getLoginUser();

            List<SysRole> roles = loginUser.getUser().getRoles();
            boolean flag=false;
            //品质主管/管理员才能打开已关闭的项目
            if(loginUser.getUser().isAdmin()){
                flag=true;
            }else {
                for (SysRole role : roles) {
                    if(role.getRoleKey().equals(RoleKey.DQA.getCode()) || role.getRoleKey().equals(RoleKey.ADMIN.getCode())){
                        flag=true;
                        break;
                    }
                }
            }
            if(!flag){
                return AjaxResult.error("你没有权限执行此操作!");
            }

            Project project = new Project();
            project.setId(id);
            project.setStatus(ProjectStatus.OPEN.getStatus());//设置为打开状态
            project.setUpdateTime(LocalDateTime.now());
            project.setUpdateUser(loginUser.getUserId());
            baseMapper.updateById(project);
            //清空项目品牌缓存
            redisCache.deleteObject("ProjectBrand");
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("打开已关闭的项目异常："+e);
            return AjaxResult.error("操作异常");
        }
    }

    @Override
    public AjaxResult queryProjectBrand() {
        List<JSONObject> brandList=new ArrayList<>();
        String cacheKey="ProjectBrand";
        brandList= redisCache.getCacheList(cacheKey);
        if(CollectionUtils.isEmpty(brandList)){
            //加锁
            Lock l =new ReentrantLock();
            try {
                l.lock();
                brandList= redisCache.getCacheList(cacheKey);
                if(CollectionUtils.isEmpty(brandList)){
                    List<Project> projectBrand = baseMapper.findProjectBrand();
                    if(!CollectionUtils.isEmpty(projectBrand)){//判断数据库查询的数据不为空
                    List<String> brandString=projectBrand.stream().map(item->{
                        return item.getCustom();
                    }).distinct().collect(Collectors.toList());
                    for (String s : brandString) {
                        List<Object> collect = projectBrand.stream().filter(f -> {
                            return f.getCustom().equals(s);
                        }).map(item -> {
                            JSONObject jsonObject=new JSONObject();
                            jsonObject.put("value",item.getModel());
                            jsonObject.put("label",item.getModel());
                            return jsonObject;
                        }).collect(Collectors.toList());
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("id",s);
                        jsonObject.put("value",s);
                        jsonObject.put("label",s);
                        jsonObject.put("children",collect);
                        brandList.add(jsonObject);
                    }
                        //设置缓存
                        redisCache.setCacheList(cacheKey,brandList);
                        //设置超时时间
                        redisCache.expire(cacheKey, 30, TimeUnit.MINUTES);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询数据异常"+e);
                return AjaxResult.error("查询项目品牌数据异常");
            } finally {
                l.unlock();
            }

        }

        return AjaxResult.success(brandList);
    }

    @Override
    public AjaxResult queryProjectCustom() {
        List<String> projectCustom = baseMapper.findProjectCustom();
        return AjaxResult.success(projectCustom);
    }


    @Override
    public AjaxResult getBugProblemTypeCount(Project project) {
        List<JSONObject> list = baseMapper.findProjectBugProblemType(project);
        List<List<Object>> result=new ArrayList<>();
        ArrayList<Object> object = new ArrayList<>();
        object.add("数量");
        object.add("type");
        result.add(object);
        for (JSONObject jsonObject : list) {
            ArrayList<Object> objects = new ArrayList<>();
            String type = jsonObject.getString("type");
            Integer count = jsonObject.getInteger("count");
            objects.add(count);
            objects.add(type);
            result.add(objects);
        }

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findSpecialCaseCount() {
        List<JSONObject> specialCase = baseMapper.findSpecialCase();
        return AjaxResult.success(specialCase);
    }

    @Override
    public AjaxResult findAdBoardTop5Date() {
        List<Project> adBoardTop5 = baseMapper.findAdBoardTop5();
        List<String> result=new ArrayList<>();
        if(!CollectionUtils.isEmpty(adBoardTop5)){
            List<String> collect = adBoardTop5.stream()
                    .sorted(Comparator.comparing(Project::getNum, Comparator.nullsLast(Comparator.reverseOrder())))
                    .map(item -> {
                        return item.getAdBoard();
                    }).collect(Collectors.toList());
            if(collect.size()>5){
                //截取前五个数据
                result=collect.subList(0, Math.min(5, collect.size()));
            }else {
                result=collect;
            }
        }

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findLcmOcTop5Date() {
        List<Project> lcmOcTop5 = baseMapper.findLcmOcTop5();
        List<String> result=new ArrayList<>();
        if(!CollectionUtils.isEmpty(lcmOcTop5)){
            List<String> collect = lcmOcTop5.stream()
                    .sorted(Comparator.comparing(Project::getNum, Comparator.nullsLast(Comparator.reverseOrder())))
                    .map(item -> {
                        return item.getLcmOc();
                    }).collect(Collectors.toList());
            if(collect.size()>5){
                //截取前五个数据
                result=collect.subList(0, Math.min(5, collect.size()));
            }else {
                result=collect;
            }
        }

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findPowerSupplyTop5Date() {
        List<Project> powerSupplyTop5 = baseMapper.findPowerSupplyTop5();
        List<String> result=new ArrayList<>();
        if(!CollectionUtils.isEmpty(powerSupplyTop5)){
            List<String> collect = powerSupplyTop5.stream()
                    .sorted(Comparator.comparing(Project::getNum, Comparator.nullsLast(Comparator.reverseOrder())))
                    .map(item -> {
                        return item.getPowerSupply();
                    }).collect(Collectors.toList());
            if(collect.size()>5){
                //截取前五个数据
                result=collect.subList(0, Math.min(5, collect.size()));
            }else {
                result=collect;
            }
        }

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult getProjectLevelTestDate(Project project) {
        List<Project> projectLevelTestCount = baseMapper.findProjectLevelTestCount(project);
        List<List> result=new ArrayList<>();
        if(!CollectionUtils.isEmpty(projectLevelTestCount)){
            //先排序
            List<Project> collect = projectLevelTestCount.stream().sorted(Comparator.comparing(Project::getNum, Comparator.nullsLast(Comparator.reverseOrder())))
                    .collect(Collectors.toList());
            List<Project> list =new ArrayList<>();
            if(collect.size()>10){//截取前十个数据
                list = collect.subList(0, Math.min(10, collect.size()));
            }else {
                list=collect;
            }
            for (Project p : list) {
                List<Object> res=new ArrayList<>();
                String str=p.getCustom()+"/"+p.getModel();
                res.add(str);
                res.add(p.getNum());
                result.add(res);
            }
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findProjectMaturity(Project project) {
        Double p=0d;
        if(StringUtils.isEmpty(project.getCustom())||StringUtils.isEmpty(project.getModel())){
            return AjaxResult.success(p);
        }
        List<Bugs> list = baseMapper.projectBugCount(project);
        if(!CollectionUtils.isEmpty(list)){
            int size = list.stream().filter(item -> {
                return item.getBugStatus().equals(BugsStatus.CLOSE.getStatus());
            }).collect(Collectors.toList()).size();
            BigDecimal bd = new BigDecimal(size)
                    .divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_UP);
            p= bd.doubleValue();//*100
        }
        return AjaxResult.success(p);
    }

    @Override
    public AjaxResult checkProjectIfClose(Long id) {
        Project project = baseMapper.selectById(id);
        return AjaxResult.success(ProjectStatus.CLOSE.getStatus().equals(project.getStatus()));
    }


}
